<template>
<!-- 地区联级选择器 -->
  <el-cascader
    :clearable="true"
    filterable
    placeholder="请选择地区"
    :options="provinceCityTree"
    :props="props"
    @change="handleItemChange"
    v-model="provinceCityIds">
  </el-cascader>
</template>
<script>
  import ComponentApi from "@/api/components/component";
  export default{
    props:{
      provinceCityValues: {
        type: Array,
        default:() => []
      },
      isChangeOnSelect: {
        type: Boolean,
        default: () => false
      },
      treeType:{
        type: Number,
        default: 1
      }
    },
    data(){
      return {
        provinceCityTree: [],
        props:{
          checkStrictly:this.isChangeOnSelect
        },
        provinceCityIds: []
      }
    },
    methods:{
      getProvinceCityTree(treeType){
        ComponentApi.treeProvinceCity({treeType:treeType})
          .then(res => {
            this.provinceCityTree = res.data;
            this.removeChildren(this.provinceCityTree);
          });
      },
      removeChildren(provinceCityTree){
        for(let i= 0,len = provinceCityTree.length;i<len;i++){
          if(provinceCityTree[i].children){
            if(provinceCityTree[i].children.length === 0){
              delete provinceCityTree[i].children;
            }else {
              this.removeChildren(provinceCityTree[i].children)
            }
          }else{
            continue;
          }
        }
      },
      handleItemChange(val){
        var cityValue = "";
        if(val.length>0){
          let province = this.provinceCityTree.filter(item => {
            return item.value == val[0]
          })
          if(val[1]){
            let city = province[0].children.filter(item => {
              return item.value == val[1];
            })
            cityValue = city[0].label
          }
          this.$emit("provinceCityChange",{
            provinceId :val[0],
            provinceName: province[0].label,
            cityId: val[1]? val[1] : "",
            cityName: cityValue,
          });
        }else{
          this.$emit("provinceCityChange",{
            provinceId :null,
            provinceName: null,
            cityId: null,
            cityName: null,
          });
        }
      }
    },
    mounted(){
      this.getProvinceCityTree(this.treeType);
    },
    watch:{
      provinceCityValues(curVal){
        let ids = [];
        curVal.forEach((item, index)=>{
          if (item){
            ids[index] = parseInt(item);
          }
        });
        this.provinceCityIds = ids;
      }
    },
  }
</script>
